# -*- coding: utf-8 -*-
"""
自建银行卡代理上分
"""
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import hashlib
import json
import logging
import random

import requests
from datetime import datetime

MCH_ID = 3
API_KEY = '31c44e0acbae4f238f8359eabce9ffbc'
# CHARGE_URL = 'http://api.maiunion.net:9003/api/v2/recharge/create/'
# QUERY_URL = 'http://219.135.56.195:8084/api/v2/recharge/query/'
CHARGE_URL = 'http://test.maiunion.net:8084/api/v2/recharge/create/'
# QUERY_URL = 'http://api.maiunion.net:9003/api/v2/recharge/query/'
#CHARGE_URL = 'http://dev.maiunion.net:9003/api/v2/recharge/query/'

PAY_SUCCESS = 1
PAY_FAIL = 2


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def get_extra_info():
    return {
        "user_info": {
            "count_withdraw":601,
            "tel":"15550019596",
            "account_day": 0,
            "count_recharge":0,
            "device_ip":"112.224.2.60",
            "chn":"kuhua",
            "user_id":184348,
            "total_bet":6321329.019999976,
            "total_recharge": 1,
            "ratio":8.359240676103433
        }
    }

def create_charge(pay_amount):
    parameter_dict = {
        'sdk_version': 'ios_5.1',
        'mch_id': MCH_ID,
        'user_id': '123456',
        'out_trade_no': random.randint(100000000000,200000000000),
        'body': u'商品',
        'pay_type': 'bankcard',
        'pay_account_num': '62221234567812',
        'pay_account_username': u'张三',
        'pay_account_bank': u'工商银行',
        'total_fee': pay_amount,
        'mch_create_ip': '127.0.0.1',
        'notify_url': 'http://219.135.56.195:8084/notify',
        'context': json.dumps(get_extra_info(), ensure_ascii=False),
        'region': '香港'
    }
    parameter_dict['sign'] = generate_sign(parameter_dict, API_KEY)
    res = requests.post(CHARGE_URL, data=parameter_dict, timeout=5).text
    return res


def query(out_trade_no):
    parameter_dict = {
        'mch_id': MCH_ID,
        'out_trade_no': out_trade_no,
        'random_num': 4444,
    }
    parameter_dict['sign'] = generate_sign(parameter_dict, API_KEY)
    res = requests.post(QUERY_URL, data=parameter_dict, timeout=5).text
    print res



def check_notify_sign(request):
    data = request.POST.dict()
    sign = data['sign']
    data.pop('sign')
    calculated_sign = generate_sign(data, API_KEY)
    if sign != calculated_sign:
        _LOGGER.info("unionagency sign: %s, calculated sign: %", sign, calculated_sign)
        raise err.ParamError('sign not pass, data: %s' % data)
    pay_id = data['trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise err.ParamError('unionagency event does not contain pay ID')

    trade_status = int(data['pay_result'])

    if trade_status == PAY_SUCCESS:
        return True
    else:
        return False

if __name__ == "__main__":
    print create_charge(100.22)
    #print query(1647748139338199040)
